package com.question.service.impl;

import com.question.constant.MessageConstant;
import com.question.context.BaseContext;
import com.question.exception.CommentNotExistException;
import com.question.exception.NoPermissionException;
import com.question.mapper.UserMapper;
import com.question.pojo.dto.CommentDTO;
import com.question.pojo.entity.Comment;
import com.question.mapper.CommentMapper;
import com.question.mapper.CommentLikeMapper;
import com.question.pojo.entity.User;
import com.question.pojo.vo.*;
import com.question.pojo.result.PageResult;
import com.question.service.CommentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class CommentServiceImpl implements CommentService {

    @Autowired
    private CommentMapper commentMapper;
    @Autowired
    private CommentLikeMapper commentLikeMpper;
    @Autowired
    private UserMapper userMapper;

    /**
     * 添加评论
     * @param commentDTO
     */
    public void addComment(CommentDTO commentDTO) {
        Comment comment = Comment.builder()
                .questionId(commentDTO.getQuestionId())
                .userId(BaseContext.getCurrentId().intValue())
                .content(commentDTO.getContent())
                .build();
        commentMapper.insertComment(comment);
    }

    /**
     * 根据题目查询评论
     * @param questionId
     * @return
     */
    public List<CommentVO> getCommentsByQuestionId(Integer questionId) {
        return commentMapper.selectCommentsByQuestionId(questionId);
    }

    /**
     * 删除评论
     * @param commentId
     */
    public void deleteCommentById(Integer commentId) {
        //判断评论是否存在
        Comment comment = commentMapper.findCommentById(commentId);
        if (comment == null) {
            throw new CommentNotExistException(MessageConstant.COMMENT_NOT_EXISTS);
        }

        //判断当前用户是否是管理员或者评论的作者
        User user = userMapper.getById(BaseContext.getCurrentId());
        boolean isAdmin = user.isAdmin();
        if (!isAdmin && !comment.getUserId().equals(BaseContext.getCurrentId().intValue())) {
            throw new NoPermissionException(MessageConstant.DELETE_NO_PERMISSION);
        }

        commentMapper.deleteCommentById(commentId);
        commentLikeMpper.deleteByCommentId(commentId);
    }




    /**
     * 管理员获取评论列表
     * @param keyword
     * @param majorId
     * @param pageNum
     * @param pageSize
     * @return
     */
    @Override
    public PageResult getAdminCommentPage(String keyword, Integer majorId, Integer pageNum, Integer pageSize) {
        int offset = (pageNum - 1) * pageSize;
        List<AdminCommentVO> list = commentMapper.selectAdminCommentList(keyword, majorId, offset, pageSize);
        int total = commentMapper.countAdminCommentList(keyword, majorId);
        return new PageResult(total, list);
    }

    /**
     * 获取评论数量
     * @return
     */
    @Override
    public List<MajorDistributionVO> getMajorDistribution() {
        return commentMapper.selectMajorDistribution();
    }

    /**
     * 获取热门问题
     * @param limit
     * @return
     */
    @Override
    public List<HotQuestionVO> getHotQuestions(Integer limit) {
        return commentMapper.selectHotQuestions(limit);
    }

    /**
     * 获取点赞用户列表
     * @param commentId
     * @return
     */
    @Override
    public List<LikeUserVO> getLikeUsers(Integer commentId) {
        return commentMapper.selectLikeUsers(commentId);
    }

    /**
     * 获取评论统计信息
     * @return
     */
    @Override
    public Map<String, Object> getCommentStats() {
        Map<String, Object> stats = new HashMap<>();

        // 总评论数
        int totalComments = commentMapper.countTotalComments();
        stats.put("totalComments", totalComments);

        // 活跃用户数（最近30天有评论的用户）
        int activeUsers = commentMapper.countActiveUsers(30);
        stats.put("activeUsers", activeUsers);

        // 总点赞数
        int totalLikes = commentMapper.countTotalLikes();
        stats.put("totalLikes", totalLikes);

        return stats;
    }

    /**
     * 获取用户统计信息
     * @param keyword
     * @param majorId
     * @param page
     * @param pageSize
     * @return
     */
    @Override
    public PageResult getUserStatPage(String keyword, Integer majorId, Integer page, Integer pageSize) {
        // 参数校验
        page = page == null || page < 1 ? 1 : page;
        pageSize = pageSize == null || pageSize < 1 ? 10 : pageSize;

        int offset = (page - 1) * pageSize;
        List<UserStatVO> list = commentMapper.selectUserStatList(keyword, majorId, offset, pageSize);
        int total = commentMapper.countUserStatList(keyword, majorId);
        return new PageResult(total, list);
    }

    /**
     * 获取专业活跃度数据
     * @return 专业活跃度列表
     */
    @Override
    public List<MajorActivityVO> getMajorActivity() {
        return commentMapper.selectMajorActivity();
    }
}
